package com.lykj.modules.shop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lykj.core.excel.util.ExcelUtil;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.core.tool.utils.DateUtil;
import com.lykj.core.tool.utils.ObjectUtil;
import com.lykj.modules.shop.entity.StoreProduct;
import com.lykj.modules.shop.excel.UserOrderExcel;
import com.lykj.modules.shop.mapper.UserOrderMapper;
import com.lykj.modules.shop.service.StoreProductService;
import com.lykj.modules.shop.service.UserBillService;
import com.lykj.modules.system.entity.User;
import com.lykj.modules.system.excel.RegionExcel;
import com.lykj.modules.system.excel.RegionImporter;
import com.lykj.modules.system.service.UserService;
import io.swagger.annotations.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.lykj.core.mp.support.Condition;
import com.lykj.core.mp.support.Query;
import com.lykj.core.tool.api.R;
import com.lykj.core.tool.utils.Func;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lykj.modules.shop.entity.UserOrder;
import com.lykj.modules.shop.vo.UserOrderVO;
import com.lykj.modules.shop.wrapper.UserOrderWrapper;
import com.lykj.modules.shop.service.UserOrderService;
import com.lykj.core.boot.ctrl.LykjController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 现金订单表 控制器
 *
 * @author cxl
 * @since 2022-01-16
 */
@RestController
@AllArgsConstructor
@RequestMapping("lykj-shop/user/order")
@Api(value = "现金订单表", tags = "现金订单表接口")
public class UserOrderController extends LykjController {

	private final UserOrderService userOrderService;
	private final UserOrderMapper userOrderMapper;
	private final StoreProductService storeProductService;
	private final UserService userService;
	private final UserBillService userBillService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入userOrder")
	public R<UserOrderVO> detail(UserOrder userOrder) {
		UserOrder detail = userOrderService.getOne(Condition.getQueryWrapper(userOrder));
		return R.data(UserOrderWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 现金订单表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入userOrder")
//	public R<IPage<UserOrderVO>> list(UserOrderVO userOrder, Query query) {
	public R<IPage<UserOrderVO>> list(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		if (query.getAscs() == null && query.getDescs() == null) {
			query.setDescs("id");
		}
		UserOrderVO userOrder = JSON.parseObject(JSON.toJSONString(params), UserOrderVO.class);
//		IPage<UserOrder> pages = userOrderService.page(Condition.getPage(query), Condition.getQueryWrapper(userOrder));
//		return R.data(UserOrderWrapper.build().pageVO(pages));
		IPage<UserOrderVO> pages = userOrderService.selectUserOrderPage(Condition.getPage(query), userOrder);
		return R.data(pages);
	}


	/**
	 * 自定义分页 现金订单表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入userOrder")
	public R<IPage<UserOrderVO>> page(UserOrderVO userOrder, Query query) {
		userOrder.setUserId(AuthUtil.getUserId());
		if (query.getAscs() == null && query.getDescs() == null) {
			query.setDescs("id");
		}
		IPage<UserOrderVO> pages = userOrderService.selectUserOrderPage(Condition.getPage(query), userOrder);
		return R.data(pages);
	}

	/**
	 * 新增 现金订单表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入userOrder")
	public R save(@Valid @RequestBody UserOrder userOrder) {
		return R.status(userOrderService.save(userOrder));
	}

	/**
	 * 导入行政区划数据
	 */
	@PostMapping("import-delivery")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "导入行政区划", notes = "传入excel")
	public R importRegion(@RequestBody List<UserOrder> userOrders) {
		String successMsg = "";
		String errorMsg = "";
		for (int i = 0; i < userOrders.size(); i++) {
			UserOrder userOrder=userOrders.get(i);
			if (ObjectUtil.isNotEmpty(userOrder.getId())&&ObjectUtil.isNotEmpty(userOrder.getDeliveryId())&&ObjectUtil.isNotEmpty(userOrder.getDeliveryName())) {
				if (userOrderMapper.setDeliveryName(userOrder.getId(),userOrder.getDeliveryName(),userOrder.getDeliveryId())<=0){
					errorMsg+="第"+i+"行,单号："+userOrder.getId()+"数据更新失败！\n";
				}else{
					successMsg+="第"+i+"行，单号："+userOrder.getId()+"数据更新成功！\\n";
				}
			}else{
				errorMsg += "第"+i+"行数据不完整，请检查！\n";
			}
		}
		if (errorMsg.equals("")) {
			return R.success(successMsg);
		}else{
			return R.fail(successMsg+errorMsg);
		}
	}


	/**
	 * 修改 现金订单表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入userOrder")
	public R update(@Valid @RequestBody UserOrder userOrder) {
		return R.status(userOrderService.updateById(userOrder));
	}

	/**
	 * 新增或修改 现金订单表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入userOrder")
	public R submit(@Valid @RequestBody UserOrder userOrder) {
		//状态-1未发货0未收货1已收货
		if (userOrder.getStatus() != 0) {
			UserOrder temp = new UserOrder();
			temp.setId(userOrder.getId());
			temp.setRemark(userOrder.getRemark());
			return R.status(userOrderService.saveOrUpdate(temp));
		}
		return R.status(userOrderService.saveOrUpdate(userOrder));
	}

	/**
	 * 删除 现金订单表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(userOrderService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 积分兑换/余额支付收货
	 */
	@PostMapping("/redeemConfirm")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "积分兑换/余额支付收货")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "订单ID", paramType = "query", required = true, dataType = "String")
	})
	public R redeemConfirm(@ApiIgnore @RequestBody Map<String, Object> params) {
		UserOrder userOrder = userOrderService.getById(Long.parseLong(params.get("id").toString()));
//		userOrder.setId(Long.parseLong(params.get("id").toString()));
		userOrder.setConfirmTime(new Date());
		userOrder.setStatus(1);//-1未发货0已发货1已收货
		userOrderService.updateById(userOrder);
		if (userOrder.getPayType() == 0) {
			// TODO 收货奖励
			userOrderService.confirmReceipt(userOrder);
		}
		return R.status(true);
	}

	/**
	 * 批量导入发货
	 */
	@PostMapping("/importData")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "批量导入发货")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "订单ID", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "deliveryName", value = "deliveryName", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "deliveryId", value = "deliveryId", paramType = "query", required = false, dataType = "String")
	})
	public R importData(@ApiIgnore @RequestParam Map<String, Object> params) {
		UserOrder userOrder = userOrderService.getById(Long.parseLong(params.get("id").toString()));
//		userOrder.setId(Long.parseLong(params.get("id").toString()));
		if (userOrder.getStatus() != 1) {
			userOrder.setDeliveryName(params.get("deliveryName").toString());
			userOrder.setDeliveryId(params.get("deliveryId").toString());
			userOrder.setDeliverTime(new Date());
			userOrder.setStatus(0);//-1未发货0未收货1已收货
			return R.status(userOrderService.updateById(userOrder));
		}
		return R.status(true);
	}

	/**
	 * 导出订单
	 */
	@GetMapping("export")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "导出订单", notes = "传入order")
	public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) {
		UserOrderVO userOrder = JSON.parseObject(JSON.toJSONString(params), UserOrderVO.class);
		if(Func.isNotEmpty(params.get("queryDate")) && !"undefined".equals(params.get("queryDate"))) {
			String[] date = params.get("queryDate").toString().split(",");
			userOrder.setStartDate(date[0]);
			userOrder.setEndDate(date[1]);
		}
		List<UserOrderExcel> list = userOrderService.export(userOrder);
		ExcelUtil.export(response, "用户订单数据" + DateUtil.time(), "用户订单数据", list, UserOrderExcel.class);
	}

	/**
	 * 手动确认收货
	 */
	@PostMapping("/delivery/{id}")
	@ApiOperationSupport(order = 33)
	@ApiOperation(value = "手动确认收货")
	public R<JSONObject> delivery(@PathVariable("id") Long id) {
		UserOrder order = userOrderService.getById(id);
		if (order != null && order.getPayType() == 2) {
			// 商品信息
			StoreProduct storeProduct = storeProductService.getById(order.getProductId());
			// 生成订单
			UserOrder userOrder = userOrderService.insertMoneyOrder(order.getTenantId(),
				order.getUserId(),
				order.getContacts(),
				order.getMobile(),
				null,
				storeProduct,
				BigDecimal.valueOf(order.getTotalNum()),
				2,
				1,
				order.getId().toString(),
				"收货");
			// TODO 收货奖励
			userOrderService.confirmReceipt(userOrder);
		}
		return R.status(true);
	}

	/**
	 * 补发第一单积分
	 */
	@PostMapping("/reissue/{id}")
	@ApiOperationSupport(order = 34)
	@ApiOperation(value = "补发第一单积分")
	public R<JSONObject> reissue(@PathVariable("id") Long id) {
		UserOrder userOrder = userOrderService.getById(id);
		if (!Func.isNull(userOrder) && Func.isNotEmpty(userOrder)) {
			// 获取用户信息
			User user = userService.getById(userOrder.getUserId());
			// 推荐人信息
			User referrer = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUid, user.getSpreadId()));
			if (referrer != null) {
				BigDecimal integral = userOrder.getPvTotalPrice();
				BigDecimal ordersTotal = userOrderService.ordersTotal(referrer.getId());
				if (integral.compareTo(ordersTotal) > -1) {
					//积分大于等于推荐人消费总额时，奖励当前推荐人消费金额相等积分
					integral = ordersTotal;
				}
				userService.inIntegral(integral, referrer.getId());
				//积分奖励记录
				userBillService.insertBill(
					referrer.getTenantId(),
					referrer.getId(),
					userOrder.getUserId(),
					userOrder.getId(),
					1,//0转出1转入
					integral,
					BigDecimal.ZERO,
					"积分奖励",
					1,//0现金1积分2贡献值
					2,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
					"第一单积分奖励,订单[" + userOrder.getId() + "],积分[" + integral + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + integral + "]"//,余额[" + referrerIntegral + "]
				);
			}
		}
		return R.status(true);
	}
}
